package com.cyl.yeepay.setvice;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cyl.h5.domain.vo.OrderPayVO;
import com.cyl.manager.oms.domain.entity.Aftersale;
import com.cyl.manager.oms.domain.entity.Order;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.yee.domain.YeeMerchantSif;
import com.cyl.wechat.WechatPayData;
import com.cyl.yeepay.config.YeePayConfig;
import com.cyl.yeepay.dto.BalanceDto;
import com.cyl.yeepay.dto.YeeComplaintInfoFlatDto;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.yeepay.yop.sdk.exception.YopClientException;
import com.yeepay.yop.sdk.service.account.AccountClient;
import com.yeepay.yop.sdk.service.account.AccountClientBuilder;
import com.yeepay.yop.sdk.service.account.model.BalanceQueryAccountInfoRespDTOResult;
import com.yeepay.yop.sdk.service.account.model.ReceiptGetReceiptRespDTOResult;
import com.yeepay.yop.sdk.service.account.model.TransferB2bOrderMgTransferOrderRespDTOResult;
import com.yeepay.yop.sdk.service.account.model.WithdrawCardQueryBankCardAccountResult;
import com.yeepay.yop.sdk.service.account.model.WithdrawCardQueryBindCardQueryRespDTOResult;
import com.yeepay.yop.sdk.service.account.model.WithdrawOrderWithdrawOrderRespDTOResult;
import com.yeepay.yop.sdk.service.account.request.TransferB2bOrderRequest;
import com.yeepay.yop.sdk.service.account.request.WithdrawCardQueryRequest;
import com.yeepay.yop.sdk.service.account.request.WithdrawOrderRequest;
import com.yeepay.yop.sdk.service.account.response.ReceiptGetResponse;
import com.yeepay.yop.sdk.service.account.response.TransferB2bOrderResponse;
import com.yeepay.yop.sdk.service.account.response.WithdrawCardQueryResponse;
import com.yeepay.yop.sdk.service.account.response.WithdrawOrderResponse;
import com.yeepay.yop.sdk.service.aggpay.AggpayClient;
import com.yeepay.yop.sdk.service.aggpay.AggpayClientBuilder;
import com.yeepay.yop.sdk.service.aggpay.model.PrePayOrderResponseDTOResult;
import com.yeepay.yop.sdk.service.aggpay.model.WechatComplaintListFlatResponseDTO;
import com.yeepay.yop.sdk.service.aggpay.request.ComplaintWechatListRequest;
import com.yeepay.yop.sdk.service.aggpay.request.PrePayRequest;
import com.yeepay.yop.sdk.service.aggpay.response.ComplaintWechatListResponse;
import com.yeepay.yop.sdk.service.aggpay.response.PrePayResponse;
import com.yeepay.yop.sdk.service.mer.MerClient;
import com.yeepay.yop.sdk.service.mer.MerClientBuilder;
import com.yeepay.yop.sdk.service.settle.SettleClient;
import com.yeepay.yop.sdk.service.settle.SettleClientBuilder;
import com.yeepay.yop.sdk.service.settle.model.SelfSettleQueryResponseDto;
import com.yeepay.yop.sdk.service.settle.request.BalanceQueryRequest;
import com.yeepay.yop.sdk.service.settle.request.ReceiptGetRequest;
import com.yeepay.yop.sdk.service.settle.response.BalanceQueryResponse;
import com.yeepay.yop.sdk.service.std.StdClient;
import com.yeepay.yop.sdk.service.std.StdClientBuilder;
import com.yeepay.yop.sdk.service.std.model.YopQueryBalanceResponseDTO;
import com.yeepay.yop.sdk.service.std.request.EndBalanceQueryRequest;
import com.yeepay.yop.sdk.service.std.response.EndBalanceQueryResponse;
import com.yeepay.yop.sdk.service.trade.TradeClient;
import com.yeepay.yop.sdk.service.trade.TradeClientBuilder;
import com.yeepay.yop.sdk.service.trade.model.ResponseRefundDTO;
import com.yeepay.yop.sdk.service.trade.request.RefundRequest;
import com.yeepay.yop.sdk.service.trade.response.RefundResponse;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class YeePayService {


    // 该Client线程安全，请使用单例模式，多次请求共用
    private static final AggpayClient aggpayClient = AggpayClientBuilder.builder().build();

    private static final TradeClient tradeClient = TradeClientBuilder.builder().build();

    private static final AccountClient accountClient = AccountClientBuilder.builder().build();
    
    private static final StdClient stdClient = StdClientBuilder.builder().build();
    
    private static final SettleClient settleClient = SettleClientBuilder.builder().build();

    @Autowired
    private ISysDeptService deptService;


    // 该Client线程安全，请使用单例模式，多次请求共用
    private static final MerClient merClient = MerClientBuilder.builder().build();
    @Autowired
    private YeePayConfig yeePayConfig;
    @Autowired
    private ISysConfigService configService;
	 // merchantNo = configService.selectConfigByKey("DEFAULT_PAYMENT_ACCOUNT");
    
    public ReceiptGetReceiptRespDTOResult receiptGet(String tradeType,String orderNo) {
    	com.yeepay.yop.sdk.service.account.request.ReceiptGetRequest  request = new com.yeepay.yop.sdk.service.account.request.ReceiptGetRequest();
        request.setParentMerchantNo(yeePayConfig.getParentMerchantNo());
        request.setTradeType(tradeType);
        request.setOrderNo(orderNo);
//        request.setRequestNo("示例值：REMIT20200327103027");
//        request.setOrderDate("orderDate_example");
//        request.setMerchantNo("merchantNo_example");
        try {
            ReceiptGetResponse response = accountClient.receiptGet(request);
            ReceiptGetReceiptRespDTOResult result =  response.getResult();
            if(result==null) {
            	throw new RuntimeException("操作失败！result null ");
           }
           if(result.getReturnCode()==null) {
           	 	throw new RuntimeException("操作失败！code is null ");
           }
           if( !"UA00000".equals(result.getReturnCode())) {
           		throw new RuntimeException("操作失败！"+result.getReturnMsg());
           }
           return result;
        } catch (YopClientException e) {
        	log.error("Exception when calling AccountClient#receiptGet, ex:", e);
       	 	throw new RuntimeException("操作失败！"+e.getMessage());
        }
    }

    
    public List<YeeComplaintInfoFlatDto>  complaintWechatList(String startTime,String endTime,String merchantNo,int page,int limit,String merchantOrderNo,String wechatOrderNo) {
    	List<YeeComplaintInfoFlatDto> retList = new ArrayList<YeeComplaintInfoFlatDto>();
        ComplaintWechatListRequest request = new ComplaintWechatListRequest();
        request.setStartTime(startTime);
        request.setEndTime(endTime);
        request.setPage(page);
        request.setLimit(limit);
        request.setMerchantNo(merchantNo);
        
        request.setMerchantOrderNo(merchantOrderNo);
        request.setWechatOrderNo(wechatOrderNo);

        request.setComplaintSource("WECHAT_BILLWECHAT_BILL");
        try {
            ComplaintWechatListResponse response = aggpayClient.complaintWechatList(request);
            WechatComplaintListFlatResponseDTO result =  response.getResult();
            if(result==null) {
            	throw new RuntimeException("操作失败！result null ");
           }
           if(result.getCode()==null) {
           	 	throw new RuntimeException("操作失败！code is null ");
           }
           if( !"00000".equals(result.getCode())) {
           		throw new RuntimeException("操作失败！"+result.getMessage());
           }
            String jsonStr = result.getList();
            retList = JSONUtil.toList(jsonStr, YeeComplaintInfoFlatDto.class);
        } catch (YopClientException e) {
        	log.error("Exception when calling AggpayClient#prePay, ex:", e);
       	 	throw new RuntimeException("操作失败！"+e.getMessage());
        }
		return retList;
    }
    
    
    /**
     * 支付
     * @param member
     * @param order
     * @param goodsName
     * @param sysDept
     * @return
     */
    public  OrderPayVO satrOrderPay(Member member,Order order,String goodsName,SysDept sysDept) {
    	
    	if(member ==null) {
            throw new RuntimeException("member不能为空");
    	}
    	
//     	if(PayNotifyController.booljzf) {
//     		Long memberId = member.getId();
//     		if(memberId.longValue() == 10003 || memberId.longValue() == 10005  || memberId.longValue() == 10008) {
//     			//测试真实
//     		}else {
//     			try {
//         			Thread.sleep(800);
//    			} catch (Exception e) {
//    				
//    			}
//                  OrderPayVO orderPayVO = new OrderPayVO();
//                  orderPayVO.setPayType(2);
//                  orderPayVO.setAppId(("appId"));
//                  orderPayVO.setNonceStr(("nonceStr"));
//                  orderPayVO.setPackage_(("package"));
//                  orderPayVO.setPaySign(("paySign"));
//                  orderPayVO.setSignType(("signType"));
//                  orderPayVO.setTimeStamp(("timeStamp"));
//                  orderPayVO.setResponseBody("假支付！");
//              	return orderPayVO;
//     		}
//    	}
     	
    	
    	if(order ==null) {
            throw new RuntimeException("order不能为空");
    	}
    	if(order.getPayId()==null) {
            throw new RuntimeException("订单支付id不能为空");
    	}
    	if(order.getCreateTime()==null) {
            throw new RuntimeException("订单创建时间不能为空");
    	}
    	 String  merchantNo = sysDept.getMerchantno();//店铺没有收款码
    	 
    	 if(merchantNo==null || merchantNo.length()<3) {//店铺上级部门没有收款码
    		 SysDept sysDeptTz = deptService.getCacheSysDept(member.getDeptTzId());
    		 merchantNo = sysDeptTz.getMerchantno();
    	 }
    	 
    	 if(merchantNo==null  || merchantNo.length()<3) {//直播间部门没有收款码
    		 SysDept sysDeptZbj = deptService.getCacheSysDept(member.getDeptZbjId());
    		 merchantNo = sysDeptZbj.getMerchantno();
    	 }
    	    
    	 if(merchantNo==null  || merchantNo.length()<3) {//系统默认收款
    		 merchantNo = configService.selectConfigByKey("DEFAULT_PAYMENT_ACCOUNT");
    	 }
    	 if(merchantNo==null) {
    		  throw new RuntimeException("默认收款账户没有配置");
    	 }
        PrePayRequest request = new PrePayRequest();
        request.setParentMerchantNo(yeePayConfig.getParentMerchantNo());//交易发起方的商编 四川小二惠选电子商务有限公司
        request.setMerchantNo(merchantNo);//收款商户编号
        request.setOrderId(order.getPayId().toString());//交易下单传入的商户收款请求号  payid
        request.setOrderAmount(order.getPayAmount());//金额  必填    元
        request.setExpiredTime(DateUtil.format(order.getCreateTime().plusMinutes(15), "yyyy-MM-dd HH:mm:ss"));//订单截止时间  格式"yyyy-MM-dd HH:mm:ss"不传默认一天
        request.setNotifyUrl(yeePayConfig.getNotifyUrl());//接收支付结果的通知地址   请参考结果通知详情 https://open.yeepay.com/docs/apis/ptssfk/options__rest__v1.0__aggpay__pre-pay#anchor7
        request.setRedirectUrl(yeePayConfig.getRedirectUrl());//页面回调地址。如使用易宝收银台需要上送前端页面回调地址
        request.setGoodsName(goodsName);//1、当商品名称超过85个字符时，易宝会默认保留前85个字符  // 2、由于微信渠道侧限制，如微信支付时该字段将自动截取前42个字符送渠道
        request.setFundProcessType("REAL_TIME");//分账订单标记 DELAY_SETTLE:需要分账 REAL_TIME:不需要分账  REAL_TIME_DIVIDE:实时分账;需同时传入divideDetail
        request.setPayWay("WECHAT_OFFIACCOUNT"); //：微信公众号支付ALIPAY_LIFE // 
        request.setChannel("WECHAT");// :微信
        request.setScene("OFFLINE");//线下
        request.setAppId(WechatPayData.appId);//微信公众号ID
        request.setUserId(member.getOpenid());//微信公众号/微信小程序为用户的openId
        request.setUserIp(yeePayConfig.getUserIp());//用户真实IP地址 已获批开通账户通的平台商，若accountLinkInfo不为空，此userIp必须与accountLinkInfo中的token所包含的IP一致
//        request.setChannelSpecifiedInfo("{\"creditPayType\":\"E_COMMERCE\",\"isAdultPay\":\"true\"}");
        request.setLimitCredit("N");//N:借贷记卡均可支付
        try {
            PrePayResponse response = aggpayClient.prePay(request);
            if(response==null) {
              	 throw new RuntimeException("操作失败！ null ");
            }
            PrePayOrderResponseDTOResult result = response.getResult();
            if(result==null) {
             	 throw new RuntimeException("操作失败！result null ");
            }
            if(result.getCode()==null) {
            	 throw new RuntimeException("操作失败！code is null ");
            }
            if( !"00000".equals(result.getCode())) {
            	throw new RuntimeException("操作失败！"+result.getMessage());
            }
//            uniqueOrderNo易宝收款订单号string
//            bankOrderld|渠道侧商户请求号string
            
            String payJson = result.getPrePayTn();
            Map<String, String> map = JSONUtil.toBean(payJson, Map.class);
            OrderPayVO orderPayVO = new OrderPayVO();
            orderPayVO.setPayType(2);
            orderPayVO.setAppId(map.get("appId"));
            orderPayVO.setNonceStr(map.get("nonceStr"));
            orderPayVO.setPackage_(map.get("package"));
            orderPayVO.setPaySign(map.get("paySign"));
            orderPayVO.setSignType(map.get("signType"));
            orderPayVO.setTimeStamp(map.get("timeStamp"));
            orderPayVO.setBankOrderId(result.getBankOrderId());
            orderPayVO.setUniqueOrderNo(result.getUniqueOrderNo());
            
            log.info("result:{}", response.getResult());
            orderPayVO.setResponseBody(JSONUtil.toJsonStr(result));
        	return orderPayVO;
        } catch (YopClientException e) {
        	log.error("Exception when calling AggpayClient#prePay, ex:", e);
       	 throw new RuntimeException("操作失败！"+e.getMessage());
        }
    }
    
    /**
     * 退款
     * @param returnApply
     * @param order
     * @return
     */
    public ResponseRefundDTO refundPay(Aftersale returnApply,Order order) {
        //请求参数
    	 RefundRequest request = new RefundRequest();
         request.setParentMerchantNo(yeePayConfig.getParentMerchantNo());//发起方商户编号。与交易下单传入的保持一致
         request.setMerchantNo(order.getMerchantno());
         request.setOrderId(order.getPayId()+"");
         request.setRefundRequestId(returnApply.getId()+"");
         request.setUniqueOrderNo(order.getUniqueorderno());
         request.setRefundAmount(returnApply.getReturnAmount().toPlainString());
         request.setDescription("用户申退款");
         if(returnApply.getType()!=null) {
        	 if(returnApply.getType().intValue() == 2) {
                 request.setDescription("用户申退货并退款");
        	 }
         }
         request.setMemo("退款");
         request.setNotifyUrl(yeePayConfig.getRefundPayNotifyUrl());
         try {
             RefundResponse response = tradeClient.refund(request);
             if(response==null) {
               	 throw new RuntimeException("操作失败！yeeRefResponse is null ");
             }
             ResponseRefundDTO result = response.getResult();
             if(result==null) {
              	 throw new RuntimeException("操作失败！yeeRefResult is null ");
             }
             if(result.getCode()==null) {
             	 throw new RuntimeException("操作失败！yeeRefResult.code is null ");
             }
             if( !"OPR00000".equals(result.getCode())) {
             	throw new RuntimeException("操作失败！yeeRefResult.code:"+result.getCode() + " msg:"+result.getMessage());
             }
             return result;
         } catch (YopClientException e) {
        	 log.error("Exception when calling TradeClient#refund, ex:", e);
          	throw new RuntimeException("操作失败！YopClientException:"+e.getMessage());
         }
    }
    
    
   
//    
//    /**
//     *  注销
//     * @param merchantNo
//     * @return
//     */
//      public boolean cancelledBankCard(YeeBankCard yeeBankCard) {
//    	  WithdrawCardModifyRequest request = new WithdrawCardModifyRequest();
//          request.setMerchantNo(yeeBankCard.getMerchantNo());
//          request.setAccountNo(yeeBankCard.getAccountNo());
//          request.setBindId(Long.parseLong(yeeBankCard.getBindId()));
//          request.setBankCode(yeeBankCard.getBankCode());
//          request.setBranchCode(yeeBankCard.getBranchCode());
//          request.setBankCardOperateType("CANCELLED");
//          boolean success = false;
//          try {
//              WithdrawCardModifyResponse response = accountClient.withdrawCardModify(request);
//              WithdrawCardModifyModifyBindCardRespDTOResult dTOResult =  response.getResult();
//              log.info("result:{}", dTOResult);
//              if("UA00000".equals(dTOResult.getReturnCode())) {
//            	  success = true;
//              }else {
//                  throw new RuntimeException("注销提现卡失败，code:"+dTOResult.getReturnCode()+" msg: "+dTOResult.getReturnMsg());
//              }
//          } catch (YopClientException e) {
//        	  log.error("Exception when calling AccountClient#withdrawCardModify, ex:", e);
//          	throw new RuntimeException("注销提现卡失败！YopClientException:"+e.getMessage());
//          }
//           
//  		return success;
//      }
      
      
//
//    /**
//     *  修改提现卡
//     * @param merchantNo
//     * @return
//     */
//      public boolean updateBankCard(YeeBankCard yeeBankCard) {
//    	  WithdrawCardModifyRequest request = new WithdrawCardModifyRequest();
//          request.setMerchantNo(yeeBankCard.getMerchantNo());
//          request.setAccountNo(yeeBankCard.getAccountNo());
//          request.setBindId(Long.parseLong(yeeBankCard.getBindId()));
//          request.setBankCode(yeeBankCard.getBankCode());
//          request.setBranchCode(yeeBankCard.getBranchCode());
//          request.setBankCardOperateType("MODIFY");
//          boolean success = false;
//          try {
//              WithdrawCardModifyResponse response = accountClient.withdrawCardModify(request);
//              WithdrawCardModifyModifyBindCardRespDTOResult dTOResult =  response.getResult();
//              log.info("result:{}", dTOResult);
//              if("UA00000".equals(dTOResult.getReturnCode())) {
//            	  success = true;
//              }else {
//                  throw new RuntimeException("修改提现卡失败，code:"+dTOResult.getReturnCode()+" msg: "+dTOResult.getReturnMsg());
//              }
//          } catch (YopClientException e) {
//        	  log.error("Exception when calling AccountClient#withdrawCardModify, ex:", e);
//          	throw new RuntimeException("修改提现卡失败！YopClientException:"+e.getMessage());
//          }
//           
//  		return success;
//      }
      
//    
//    /**
//     *  添加提现卡
//     * @param merchantNo
//     * @return
//     */
//      public Long addBankCard(YeeBankCard yeeBankCard) {
//    	  WithdrawCardBindBindCardRespDTOResult dTOResult = null;
//    	  WithdrawCardBindRequest request = new WithdrawCardBindRequest();
//          request.setMerchantNo(yeeBankCard.getMerchantNo());
//          request.setBankCardType(yeeBankCard.getBankCardType());
//          request.setAccountNo(yeeBankCard.getAccountNo());
//          request.setBankCode(yeeBankCard.getBankCode());
//          request.setBranchCode(yeeBankCard.getBranchCode());
//          Long bindId = null;
//          try {
//              WithdrawCardBindResponse response = accountClient.withdrawCardBind(request);
//              dTOResult =  response.getResult();
//              log.info("result:{}", dTOResult);
//              if("UA00000".equals(dTOResult.getReturnCode())) {
//            	  bindId = dTOResult.getBindId();
//              }else {
//                  throw new RuntimeException("添加提现卡失败，code:"+dTOResult.getReturnCode()+" msg: "+dTOResult.getReturnMsg());
//              }
//          } catch (YopClientException e) {
//        	  log.error("YopClientException Exception when calling AccountClient#withdrawCardBind, ex:", e);
//            	throw new RuntimeException("添加提现卡失败！YopClientException:"+e.getMessage());
//          }
//           
//  		return bindId;
//      }
//      
    
  /**
   * 提现卡查询
   * @param merchantNo
   * @return
   */
    public List<WithdrawCardQueryBankCardAccountResult> getBankCardAccountList(String merchantNo) {
    	WithdrawCardQueryRequest request = new WithdrawCardQueryRequest();
    	List<WithdrawCardQueryBankCardAccountResult>  bankCardAccountList = null;
        request.setMerchantNo(merchantNo);
        try {
            WithdrawCardQueryResponse response = accountClient.withdrawCardQuery(request);
            WithdrawCardQueryBindCardQueryRespDTOResult dTOResult =  response.getResult();
            log.info("result:{}", dTOResult);
            if("UA00000".equals(dTOResult.getReturnCode())) {
                bankCardAccountList = response.getResult().getBankCardAccountList();
            }else {
                throw new RuntimeException("提现卡查询失败，code:"+dTOResult.getReturnCode()+" msg: "+dTOResult.getReturnMsg());
            }
        } catch (YopClientException e) {
        	log.error("YopClientException Exception when calling AccountClient#withdrawCardQuery, ex:", e);
          	throw new RuntimeException("提现卡查询失败！YopClientException:"+e.getMessage());
        }
		return bankCardAccountList;
    }
    
    
    public String getBaseMerchantNoH5(Long deptZbjId){
    	String  merchantNo = null;
   		 try {
  	    	if(deptZbjId!=null) {
  	    		SysDept sysDeptZbj = deptService.getCacheSysDept(deptZbjId);
  	    		if(sysDeptZbj!=null) {
       	    		merchantNo = sysDeptZbj.getMerchantno();
  	    		}
  	    	}
		 } catch (Exception e) {
		 }
   	 if(merchantNo== null || "".equals(merchantNo)) {
   		 merchantNo = configService.selectConfigByKey("DEFAULT_PAYMENT_ACCOUNT");
     }
   	 return merchantNo;
   }
    
    
    public String getBaseMerchantNo(String merchantNo){
    	 
    	
    	 if(merchantNo== null || "".equals(merchantNo)) {
    		 try {
    	  	    	Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
    	  	    	if(qrDeptZbjId!=null) {
    	  	    		SysDept sysDeptZbj = deptService.getCacheSysDept(qrDeptZbjId);
    	  	    		if(sysDeptZbj!=null) {
            	    		merchantNo = sysDeptZbj.getMerchantno();
    	  	    		}
    	  	    	}
			 } catch (Exception e) {
			 }
         }
    	
    	 
    	 
    	 if(merchantNo== null || "".equals(merchantNo)) {
    		 
    		 merchantNo = configService.selectConfigByKey("DEFAULT_PAYMENT_ACCOUNT");
         }
    	 return merchantNo;
    }
    
    /**
     * 查询 余额 商户可结算金额  未结算金额
     * @param date
     * @param merchantNo
     * @return
     */
    public  BalanceDto endBalanceAddBalanceQuery(String date,String merchantNo) {
      
       merchantNo = getBaseMerchantNo(merchantNo);
    	
  	   // * 余额  查询格式应为yyyy-MM-dd,日期需小于今天
  	   String balance = null;
  	   // * 商户可结算金额。商户可结算但未结算的金额
  	   BigDecimal settlableAmount = null;
  	   // * 未结算金额。未结算金额&#x3D;可结算但未结算的金额+不可结算金额（未到结算周期的交易汇总金额）
  	   BigDecimal unsettledAmount = null;

 	   String endBalanceQueryMsg = null;

 	   String balanceQueryMsg = null;
 	   try {
 		  balance =  endBalanceQuery(date, merchantNo).getBalance();
	   } catch (Exception e) {
		   endBalanceQueryMsg = e.getMessage();
	   }
  	   
	 	try {
	 		    SelfSettleQueryResponseDto  selfSettleBalanceDto =  balanceQuery(date, merchantNo);
	 		  	settlableAmount = selfSettleBalanceDto.getSettlableAmount();
	 		  	unsettledAmount = selfSettleBalanceDto.getUnsettledAmount();
		} catch (Exception e) {
			   balanceQueryMsg = e.getMessage();
		}
		return new BalanceDto(balance, settlableAmount, unsettledAmount, endBalanceQueryMsg, balanceQueryMsg);
    }
    
    public BalanceQueryAccountInfoRespDTOResult balanceQueryByZj() {
    	BalanceQueryAccountInfoRespDTOResult response = null;
        com.yeepay.yop.sdk.service.account.request.BalanceQueryRequest request = new com.yeepay.yop.sdk.service.account.request.BalanceQueryRequest();
        request.setMerchantNo(getBaseMerchantNo(null));
        try { 
        	response = accountClient.balanceQuery(request).getResult();
        } catch (YopClientException e) {
          	throw new RuntimeException("日终余额查询失败！YopClientException:"+e.getMessage());
        }
		return response;
    }
    
    
    /**
     * 日终余额查询
     * @param date
     * @param merchantNo
     * @return
     */
    public  YopQueryBalanceResponseDTO endBalanceQuery(String date,String merchantNo) {
    	if(date==null || "".equals(date)) {
            Date newDate = DateUtil.offsetDay(new Date(), -1);
            date = DateUtil.formatDate(newDate);
    	}
        merchantNo = getBaseMerchantNo(merchantNo);
    	YopQueryBalanceResponseDTO dTOResult = null;
        EndBalanceQueryRequest request = new EndBalanceQueryRequest();
        request.setDate(date);
        request.setMerchantNo(merchantNo);
        try {
            EndBalanceQueryResponse response = stdClient.endBalanceQuery(request);
            log.info("result:{}", response.getResult());
            dTOResult =  response.getResult();
            log.info("result:{}", dTOResult);
            if("00000".equals(dTOResult.getCode())) {
            	 dTOResult =  response.getResult();
            }else {
                throw new RuntimeException("日终余额查询失败，code:"+dTOResult.getCode()+" msg: "+dTOResult.getMessage());
            }
        } catch (YopClientException e) {
          	throw new RuntimeException("日终余额查询失败！YopClientException:"+e.getMessage());
        }
		return dTOResult;
    }
    
  
    /**
     * 待结算金额查询
     * @param date
     * @param merchantNo
     * @return
     */
    public  SelfSettleQueryResponseDto balanceQuery(String date,String merchantNo) {
    	if(date==null || "".equals(date)) {
    		DateUtil.formatDate(new Date());
    	}
    	
        merchantNo = getBaseMerchantNo(merchantNo);
    	SelfSettleQueryResponseDto dTOResult = null;
        BalanceQueryRequest request = new BalanceQueryRequest();
        request.setMerchantNo(merchantNo);
        request.setParentMerchantNo(yeePayConfig.getParentMerchantNo());//交易发起方的商编 四川小二惠选电子商务有限公司
        request.setOperatePeriod("ALL");
        
        DateTime dateTime = DateTime.parse(date, DateTimeFormat.forPattern("yyyy-MM-dd"));
        request.setEndTime(dateTime);
        try {
            BalanceQueryResponse response = settleClient.balanceQuery(request);
            dTOResult =  response.getResult();
            log.info("result:{}", dTOResult);
            if("000000".equals(dTOResult.getCode())) {
            	dTOResult =  response.getResult();
            }else {
                throw new RuntimeException("待结算金额查询，code:"+dTOResult.getCode()+" msg: "+dTOResult.getMessage());
            }
        } catch (YopClientException e) {
        	log.error("Exception when calling SettleClient#balanceQuery, ex:", e);
          	throw new RuntimeException("待结算金额查询！YopClientException:"+e.getMessage());

        }
		return dTOResult;
    }
    
    /**
     * 收手续费
     * @param args
     */
    public TransferB2bOrderMgTransferOrderRespDTOResult transferB2bByFee(YeeMerchantSif yeeMerchantSif) {
    	
    	String feeMerchantNo = yeePayConfig.getFeeMerchantNo();
    	String feeAccountType = yeePayConfig.getFeeAccountType();

    	TransferB2bOrderMgTransferOrderRespDTOResult dTOResult = null;
        TransferB2bOrderRequest request = new TransferB2bOrderRequest();
        request.setParentMerchantNo(yeePayConfig.getParentMerchantNo());//交易发起方的商编 四川小二惠选电子商务有限公司
        request.setRequestNo("F"+DateUtil.format(new Date(), "yyMMddHHmmssSSS")+yeeMerchantSif.getId());//商户请求号，由商户自定义生成;
        request.setFromMerchantNo(yeeMerchantSif.getFromMerchantNo());//转出方商户编号        
        request.setToMerchantNo(feeMerchantNo);//转入方商户编号
        if((feeAccountType==null)) {
            request.setToAccountType("FUND_ACCOUNT");//转入方账户类型 手续费账户
        }else {
            request.setToAccountType(feeAccountType);//转入方账户类型
        }
//        FUND_ACCOUNT:商户支付账户
//        MARKET_ACCOUNT:营销账户（当为此参数时，fromMerchantNo和toMerchantNo需要保持一致）
//        FEE_ACCOUNT:手续费账户（当为此参数时，fromMerchantNo和toMerchantNo需要保持一致）
//        SPECIAL_FUND_ACCOUNT:专款账户（当为此参数时，toAccountNo不能为空）
//        示例值：默认FUND_ACCOUNT
        BigDecimal orderAmount =  yeeMerchantSif.getFeeAmount();//转账金额+手续费
        request.setOrderAmount(orderAmount.toString());
        request.setUsage("他卡手续费");//用途
//        request.setFeeChargeSide("");//手续费承担方
//        枚举值
//        OUTSIDE:转出方承担,
//        INSIDE:转入方承担(若不传默认转出方承担)
//        示例值：当商户承担且计费方式为预付实扣或后收时，不支持转入方承担；当平台商或服务商承担时无需指定此手续费承担方；
//        request.setNotifyUrl("notifyUrl_example");//通知转入方url 转账接收方通知地址，不传则不通知，且转入方需具备自己的app_key才能获取到通知
//        
//        request.setRiskInfo("riskInfo_example");
//        request.setToAccountNo("toAccountNo_example");
//        request.setVerifyType("PWD");//核验方式 密码校验
//        request.setVerifyValue("verifyValue_example");//当核验方式为PWD时，该参数为密码密文，字段必填
        try {
            TransferB2bOrderResponse response = accountClient.transferB2bOrder(request);
             dTOResult =  response.getResult();
        } catch (YopClientException e) {
        	 dTOResult = new TransferB2bOrderMgTransferOrderRespDTOResult();
        	 dTOResult.setReturnCode("YopClientExceptionB2BFEE");
        	 dTOResult.setReturnMsg("手续费-下单失败！YopClientExceptionB2BFEE:"+e.getMessage());
        	log.error("YopClientException Exception when calling AccountClient#transferB2bFEEOrder, ex:", e);
        }
		return dTOResult;
    }
    
 
    /**
     * 转账-下单
     * @param args
     */
    public TransferB2bOrderMgTransferOrderRespDTOResult transferB2bOrder(YeeMerchantSif yeeMerchantSif) {
    	TransferB2bOrderMgTransferOrderRespDTOResult dTOResult = null;
        TransferB2bOrderRequest request = new TransferB2bOrderRequest();
        request.setParentMerchantNo(yeePayConfig.getParentMerchantNo());//交易发起方的商编 四川小二惠选电子商务有限公司
       
        		
        request.setRequestNo("B"+DateUtil.format(new Date(), "yyMMddHHmmssSSS")+yeeMerchantSif.getId());//商户请求号，由商户自定义生成;
        
        request.setFromMerchantNo(yeeMerchantSif.getFromMerchantNo());//转出方商户编号
        request.setToMerchantNo(yeeMerchantSif.getToMerchantNo());//转入方商户编号
        if((yeeMerchantSif.getToAccountType()==null)) {
            request.setToAccountType("FUND_ACCOUNT");//转入方账户类型
        }else {
            request.setToAccountType(yeeMerchantSif.getToAccountType());//转入方账户类型
        }
//        FUND_ACCOUNT:商户支付账户
//        MARKET_ACCOUNT:营销账户（当为此参数时，fromMerchantNo和toMerchantNo需要保持一致）
//        FEE_ACCOUNT:手续费账户（当为此参数时，fromMerchantNo和toMerchantNo需要保持一致）
//        SPECIAL_FUND_ACCOUNT:专款账户（当为此参数时，toAccountNo不能为空）
//        示例值：默认FUND_ACCOUNT
        BigDecimal orderAmount =  yeeMerchantSif.getOrderAmount();//转账金额+手续费
        request.setOrderAmount(orderAmount.toString());
        request.setUsage(yeeMerchantSif.getCmtjyy());//用途
//        request.setFeeChargeSide("");//手续费承担方
//        枚举值
//        OUTSIDE:转出方承担,
//        INSIDE:转入方承担(若不传默认转出方承担)
//        示例值：当商户承担且计费方式为预付实扣或后收时，不支持转入方承担；当平台商或服务商承担时无需指定此手续费承担方；
//        request.setNotifyUrl("notifyUrl_example");//通知转入方url 转账接收方通知地址，不传则不通知，且转入方需具备自己的app_key才能获取到通知
//        
//        request.setRiskInfo("riskInfo_example");
//        request.setToAccountNo("toAccountNo_example");
//        request.setVerifyType("PWD");//核验方式 密码校验
//        request.setVerifyValue("verifyValue_example");//当核验方式为PWD时，该参数为密码密文，字段必填
        try {
            TransferB2bOrderResponse response = accountClient.transferB2bOrder(request);
             dTOResult =  response.getResult();
        } catch (YopClientException e) {
        	 dTOResult = new TransferB2bOrderMgTransferOrderRespDTOResult();
        	 dTOResult.setReturnCode("YopClientExceptionB2B");
        	 dTOResult.setReturnMsg("转账-下单失败！YopClientExceptionB2B:"+e.getMessage());
        	log.error("YopClientException Exception when calling AccountClient#transferB2bOrder, ex:", e);
//          	throw new RuntimeException("转账-下单失败！YopClientException:"+e.getMessage());

        }
		return dTOResult;
    }
    
    

    /**
     * 提现-下单
     * @param args
     */
    public WithdrawOrderWithdrawOrderRespDTOResult transferB2cOrder(YeeMerchantSif yeeMerchantSif) {
    	WithdrawOrderWithdrawOrderRespDTOResult dTOResult = null;
        WithdrawOrderRequest request = new WithdrawOrderRequest();
        request.setParentMerchantNo(yeePayConfig.getParentMerchantNo());//业务发起方商编 （标准商户收付款方案中此参数与商编一致，平台商户收付款方案中此参数为平台商商户编号）
        request.setRequestNo("C"+DateUtil.format(new Date(), "yyMMddHHmmssSSS")+yeeMerchantSif.getId());// 商户请求号     由商户自定义生成
        request.setMerchantNo(yeeMerchantSif.getToMerchantNo());//商户编号
        request.setBankCardId(yeeMerchantSif.getBindId());//提现卡ID  添加提现账户时易宝生成的提现卡ID，与提现卡卡号至少填写一个
        request.setBankAccountNo(yeeMerchantSif.getAccountNo());//提现账号   与提现卡ID至少填写一个
        request.setReceiveType("REAL_TIME");//REAL_TIME:实时到账  TWO_HOUR:2 小时到账  NEXT_DAY:次日到账（无特殊情况资金于次日上午 7 点左右到银行账户中）
        request.setOrderAmount(yeeMerchantSif.getOrderAmount());//提现金额
        request.setNotifyUrl(yeePayConfig.getNotifyOutUrl());//回调通知地址

        request.setRemark(yeeMerchantSif.getB2cBz());//银行附言
        request.setTerminalType("PC");//终端类型
//        request.setFeeDeductType("feeDeductType_example");//手续费收取方式
//        枚举值
//        OUTSIDE:外扣
//        OUT_TO_IN:外扣转内扣
//        INSIDE:内扣
        request.setAccountType(yeeMerchantSif.getToAccountType());//  账户类型
//        枚举值
//        FUND_ACCOUNT:资金账户
//        MARKET_ACCOUNT:营销账户
//        FEE_ACCOUNT:手续费账户
        request.setMacAddress(yeeMerchantSif.getMacAddress());//设备mac地址
        request.setWithdrawModel("INNER_ACCOUNT_WITHDRAW");//提现模式 默认为易宝内部账户模式
//        request.setDebitBankAccountBookNo("debitBankAccountBookNo_example");
//        request.setVerifyType("PWD");//核验方式
//        request.setVerifyValue("verifyValue_example");//当核验方式为PWD时，该参数为密码密文，字段必填
        try {
            WithdrawOrderResponse response = accountClient.withdrawOrder(request);
            dTOResult =  response.getResult();
            log.info("result:{}", dTOResult);
        } catch (YopClientException e) {
          	dTOResult = new WithdrawOrderWithdrawOrderRespDTOResult();
          	dTOResult.setReturnCode("YopClientExceptionB2C");
          	dTOResult.setReturnMsg("转账-下单失败！YopClientExceptionB2C:"+e.getMessage());
        	log.error("Exception when calling AccountClient#withdrawOrder, ex:", e);
        }
		return dTOResult;

    }
    
    
   

//    public static void main(String[] args) {
//        BankAccountOpenQueryRequest request = new BankAccountOpenQueryRequest();
//        request.setMerchantNo("merchantNo_example");
//        try {merClient.
//            BankAccountOpenQueryResponse response = merClient.bankAccountOpenQuery(request);
//            LOGGER.info("result:{}", response.getResult());
//        } catch (YopClientException e) {
//            LOGGER.error("Exception when calling MerClient#bankAccountOpenQuery, ex:", e);
//        }
//    }
    
    
    // 该Client线程安全，请使用单例模式，多次请求共用     private static final MerClient api = MerClientBuilder.builder().build();
//    public  RegisterContributeIndexV2Response registerContributeIndexV2() {
//    	 RegisterContributeIndexV2Request request = new RegisterContributeIndexV2Request();
//         request.setRequestNo("示例值：REQ6437657876");
//         request.setNotifyUrl("示例值：http://www.shili111.com");
//         request.setReturnUrl("示例值：http://www.shili.com");
//         request.setMobile("159****8288");
//         request.setName("示例值：张三");
//         request.setIdCardNo("示例值：430422199001236704");
//         request.setWalletUserNo("示例值：User89849");
//         try {
//             RegisterContributeIndexV2Response response = api.registerContributeIndexV2(request);
//             LOGGER.info("result:{}", response.getResult());
//         } catch (YopClientException e) {
//             LOGGER.error("Exception when calling MerClient#registerContributeIndexV2, ex:", e);
//         }
//    }
    
    
    
}
